var express = require('express');
var app = express();
const server = require("http").createServer(app);
const session = require("express-session");
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var createError = require("http-errors");
// 环境变量配置引用
const dotenv = require("dotenv");
dotenv.config();
// 全局使用moment时间格式化
global.moment = require("moment");
// 引入路由
const arrRoutes = require("./utils/routes");
// socket
require('./routes/socket')(server);
// 模板引擎
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.use(cookieParser("sessiontest"));
// session储存
app.use(
  session({
    secret: "sessiontest", //与cookieParser中的一致
    resave: true,
    saveUninitialized: true,
  })
);
// 前端解决跨域问题
app.all("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  next();
});
app.use(logger('dev'));
// 解析json数据
app.use(express.json({ limit: "50mb" }));
// 解析中间件
app.use(express.urlencoded({ limit: "50mb", extended: true }));
// 静态资源托管
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "upload")));
// 路由挂载
for (const route of arrRoutes) {
  console.log("路由列表", route);
  app.use(route.path, require(route.component));
}
// 捕获404并转发到错误处理
app.use(function(req, res, next) {
  next(createError(404));
});

// 错误处理
app.use(function(err, req, res, next) {
  // 设置局部变量，仅提供开发中的错误
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

  // 呈现错误页面
  res.status(err.status || 500);
  res.render("error");
});
// 监听端口
server.listen(5000, () => {
  console.log("服务启动成功  监听端口5000");
});


module.exports = app;
